<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="queryParams.name"
              placeholder="搜索模板名称"
              clearable
              @keyup.enter.native="handleQuery"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="handleQuery"
              />
            </el-input>
          </el-col>
          <el-col :span="16" class="text-right">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd"
            >新增模板
            </el-button>
          </el-col>
        </el-row>
      </div>

      <el-table
        v-loading="loading"
        :data="templateList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="模板名称" prop="name" min-width="150" show-overflow-tooltip/>
        <el-table-column label="模板描述" prop="description" min-width="200" show-overflow-tooltip/>
        <el-table-column label="总分" prop="totalScore" width="100" align="center"/>
        <el-table-column label="题目数" prop="questionCount" width="100" align="center"/>
        <el-table-column label="创建人" prop="createByName" width="120" align="center"/>
        <el-table-column label="创建时间" prop="createTime" width="160" align="center"/>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              style="color: #f56c6c"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称"/>
        </el-form-item>
        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input-number
            v-model="form.totalScore"
            :precision="2"
            :step="1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="题目数" prop="questionCount">
          <el-input-number
            v-model="form.questionCount"
            :min="1"
          />
        </el-form-item>

        <!-- 知识点选择 -->
        <el-form-item label="知识点选择">
          <el-popover
            placement="bottom-start"
            width="400"
            trigger="click"
            v-model="categoryPopoverVisible"
          >
            <div class="category-selector">
              <el-input
                v-model="categoryFilterText"
                placeholder="输入分类名称搜索"
                clearable
                size="small"
                prefix-icon="el-icon-search"
              />
              <el-tree
                ref="categoryTree"
                class="filter-tree"
                :data="categoryTree"
                :props="categoryProps"
                :filter-node-method="filterCategoryNode"
                node-key="id"
                highlight-current
                @node-click="handleCategoryNodeClick"
              />
            </div>
            <el-tag
              slot="reference"
              type="info"
              closable
              @close="removeSelectedCategory"
              v-if="selectedCategory"
            >
              {{ selectedCategory.name }}
            </el-tag>
            <el-button
              slot="reference"
              type="text"
              icon="el-icon-folder-opened"
              v-else
            >
              选择分类
            </el-button>
          </el-popover>
          <el-select
            v-model="form.knowledgeIds"
            multiple
            filterable
            placeholder="请选择知识点"
            style="width: 100%; margin-top: 10px;"
            :disabled="!selectedCategory"
          >
            <el-option
              v-for="item in knowledgeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 题型配置 -->
        <el-form-item label="题型配置" prop="questionConfig">
          <div class="type-config-container">
            <div v-for="(type, index) in typeConfigs" :key="index" class="type-config-item">
              <el-row :gutter="20">
                <el-col :span="7" :sm="8" :md="8">
                  <el-select
                    v-model="type.typeId"
                    placeholder="请选择题型"
                    style="width: 100%"
                    @change="handleTypeChange(index)"
                  >
                    <el-option
                      v-for="item in typeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                  <div class="config-tip">选择题目类型</div>
                </el-col>
                <el-col :span="5" :sm="6" :md="6">
                  <el-input-number
                    v-model="type.count"
                    :min="0"
                    :max="100"
                    label="题目数量"
                    @change="calculateTotalScore"
                    style="width: 100%"
                  />
                  <div class="config-tip">题目数量</div>
                </el-col>
                <el-col :span="5" :sm="6" :md="6">
                  <el-input-number
                    v-model="type.score"
                    :min="0.5"
                    :max="100"
                    :step="0.5"
                    label="每题分数"
                    @change="calculateTotalScore"
                    style="width: 100%"
                  />
                  <div class="config-tip">每题分数</div>
                </el-col>
                <el-col :span="5" :sm="4" :md="4" class="action-col">
                  <div class="action-buttons">
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      size="mini"
                      @click="removeTypeConfig(index)"
                      v-if="typeConfigs.length > 1"
                      class="delete-btn"
                    />
                  </div>
                  <div class="type-total">
                    小计：{{ (type.count * type.score).toFixed(1) }}分
                  </div>
                </el-col>
              </el-row>
              <div class="type-total">
                该题型总分：{{ (type.count * type.score).toFixed(1) }} 分
              </div>
            </div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="addTypeConfig"
            >
              添加题型
            </el-button>
            <div class="total-score-summary">
              <el-tag type="success" size="medium">
                当前总分：{{ totalScore.toFixed(1) }} 分
              </el-tag>
              <el-tag type="info" size="medium" style="margin-left: 10px;">
                题目总数：{{ totalQuestionCount }} 题
              </el-tag>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageTemplate, getTemplate, saveTemplate, deleteTemplate } from '@/api/paper2/template'
import { listQuestionTypes } from '@/api/question2/type'
import { getCategoryTree, listKnowledge } from '@/api/question2/category'

export default {
  name: 'TemplateList',
  data() {
    return {
      totalScore: 0,
      totalQuestionCount: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      // 模板列表
      templateList: [],
      total: 0,
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 对话框标题
      dialogTitle: '',
      // 是否显示对话框
      dialogVisible: false,
      // 表单数据
      form: {
        id: undefined,
        name: '',
        description: '',
        totalScore: 100,
        questionCount: 20,
        knowledgeIds: [],
        configJson: ''
      },
      // 表单验证
      rules: {
        name: [
          {required: true, message: '模板名称不能为空', trigger: 'blur'}
        ],
        totalScore: [
          {required: true, message: '总分不能为空', trigger: 'blur'}
        ],
        questionCount: [
          {required: true, message: '题目数不能为空', trigger: 'blur'}
        ],
        // questionConfig: [
        //   {required: true, message: '请至少配置一种题型', trigger: 'blur'}
        // ]
      },
      // 题型列表
      typeList: [],
      // 题型配置
      typeConfigs: [
        {typeId: undefined, count: 0, score: 0}
      ],
      // 分类树相关
      categoryTree: [],
      categoryProps: {
        label: 'name',
        children: 'children'
      },
      categoryFilterText: '',
      categoryPopoverVisible: false,
      selectedCategory: null,
      knowledgeList: []
    }
  },
  created() {
    this.getList()
    this.loadQuestionTypes()
    this.loadCategoryTree()
  },
  methods: {
    calculateTotalScore() {
      // 计算总分
      this.totalScore = this.typeConfigs.reduce((sum, type) => {
        return sum + (type.count * type.score)
      }, 0)

      // 计算总题数
      this.totalQuestionCount = this.typeConfigs.reduce((sum, type) => {
        return sum + type.count
      }, 0)

      // 自动更新表单中的总分和题目数
      this.form.totalScore = this.totalScore
      this.form.questionCount = this.totalQuestionCount
    },
    /** 查询模板列表 */
    getList() {
      this.loading = true
      pageTemplate(this.queryParams).then(response => {
        this.templateList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 加载题型列表 */
    loadQuestionTypes() {
      listQuestionTypes().then(response => {
        this.typeList = response.data
      })
    },
    /** 加载分类树 */
    loadCategoryTree() {
      getCategoryTree().then(response => {
        this.categoryTree = response.data
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetForm()
      this.dialogTitle = '新增模板'
      this.dialogVisible = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetForm()
      const id = row.id
      getTemplate(id).then(response => {
        this.form = response.data
        // 解析题型配置
        if (this.form.configJson) {
          const config = JSON.parse(this.form.configJson)
          if (config.types) {
            this.typeConfigs = config.types.map(type => ({
              typeId: this.typeList.find(t => t.name === type.name)?.id,
              count: type.count,
              score: type.score
            }))
          }
        }
        this.dialogTitle = '修改模板'
        this.dialogVisible = true
      })
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(this.typeConfigs)
          // 验证题型配置
          // if (this.typeConfigs.length === 0 ||
          //   this.typeConfigs.some(t => !t.typeId || t.count <= 0 || t.score <= 0)) {
          //   this.$message.error('请正确配置所有题型')
          //   return
          // }
          // 验证题型配置
          // if (this.typeConfigs.length === 0 || this.typeConfigs.some(t => !t.typeId || t.count <= 0 || t.score <= 0)) {
          //   this.$message.error('请正确配置所有题型')
          //   return
          // }


          // this.form.configJson = JSON.stringify(config)
          this.form.questionTypeConfig = this.typeConfigs.map(type => {
            const typeInfo = this.typeList.find(t => t.id === type.typeId)
            return {
              typeId: type.typeId,
              name: typeInfo.name,
              count: type.count,
              score: type.score
            }
          })

          saveTemplate(this.form).then(response => {
            this.$modal.msgSuccess('保存成功')
            this.dialogVisible = false
            this.getList()
          })
        }
      })
    },
    /** 重置表单 */
    resetForm() {
      this.form = {
        id: undefined,
        name: '',
        description: '',
        totalScore: 100,
        questionCount: 20,
        knowledgeIds: [],
        configJson: ''
      }
      this.typeConfigs = [
        {typeId: undefined, count: 0, score: 0}
      ]
      this.selectedCategory = null
      this.knowledgeList = []
    },
    /** 添加题型配置 */
    addTypeConfig() {
      this.typeConfigs.push({
        typeId: undefined,
        count: 1,
        score: 1
      })
      this.calculateTotalScore()
    },
    /** 移除题型配置 */
    removeTypeConfig(index) {
      this.typeConfigs.splice(index, 1)
      this.calculateTotalScore()
    },
    /** 题型变化处理 */
    // 在handleTypeChange方法中调用calculateTotalScore
    handleTypeChange(index) {
      this.calculateTotalScore()
    },
    /** 分类树节点过滤 */
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    /** 分类节点点击事件 */
    handleCategoryNodeClick(data) {
      if (data.isKnowledge === 1) {
        this.$message.warning('请选择分类，而不是知识点')
        return
      }
      this.selectedCategory = data
      this.categoryPopoverVisible = false
      this.loadKnowledgeByCategory(data.id)
    },
    /** 移除选中的分类 */
    removeSelectedCategory() {
      this.selectedCategory = null
      this.knowledgeList = []
      this.form.knowledgeIds = []
    },
    /** 根据分类加载知识点 */
    loadKnowledgeByCategory(categoryId) {
      listKnowledge({parentId: categoryId}).then(response => {
        this.knowledgeList = response.data
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = [row.id]
      this.$modal.confirm('确定要删除选中的模板吗？').then(() => {
        return deleteTemplate(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.type-config-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.type-config-item {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.category-selector {
  padding: 10px;

  .filter-tree {
    margin-top: 10px;
    max-height: 300px;
    overflow-y: auto;
  }
}

.config-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  line-height: 1.2;
}

.type-total {
  font-size: 13px;
  color: #666;
  margin-top: 5px;
  text-align: right;
  padding-right: 10px;
}

.total-score-summary {
  margin-top: 15px;
  text-align: right;
}

.question-item:hover .delete-button {
  visibility: visible;
}

.delete-button {
  visibility: hidden;
  /* 其他样式 */
}

/* 响应式样式 */
.type-config-container {
  .type-config-item {
    margin-bottom: 15px;
    padding: 10px;
    background-color: #f9f9f9;
    border-radius: 4px;
    position: relative;

    .action-col {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      justify-content: space-between;

      .action-buttons {
        margin-bottom: 5px;
      }

      .type-total {
        font-size: 12px;
        color: #666;
      }
    }

    .delete-btn {
      margin-left: 0;
    }
  }

  @media (max-width: 768px) {
    .type-config-item {
      .el-col {
        margin-bottom: 10px;

        &:last-child {
          margin-bottom: 0;
        }
      }

      .action-col {
        flex-direction: row;
        align-items: center;
        justify-content: flex-end;

        .action-buttons {
          margin-bottom: 0;
          margin-right: 10px;
        }

        .type-total {
          margin-left: 10px;
        }
      }
    }
  }
}

.config-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
